package com.zkyc.framework.website.service.impl;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.zkyc.framework.common.constant.NumberConstant;
import com.zkyc.framework.common.exception.ResultCode;
import com.zkyc.framework.common.pojo.*;
import com.zkyc.framework.common.utils.WebsiteUtil;
import com.zkyc.framework.common.vo.ResultVO;
import com.zkyc.framework.website.client.RoleClient;
import com.zkyc.framework.website.client.UserClient;
import com.zkyc.framework.common.mapper.CenterMapper;
import com.zkyc.framework.common.mapper.OrganizationMapper;
import com.zkyc.framework.website.mapper.MoudleMapper;
import com.zkyc.framework.website.service.OrganizationService;
import com.zkyc.framework.website.strategy.StrategyEnum;
import com.zkyc.framework.website.strategy.StrategyHandler;
import com.zkyc.framework.website.util.TokenUserUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * (Organization)表服务实现类
 *
 * @author libingchuan
 * @since 2022-05-25 16:06:14
 */
@Service("organizationService")
public class OrganizationServiceImpl implements OrganizationService {
    @Resource
    private OrganizationMapper organizationMapper;


    @Autowired
    private UserClient userClient;

    @Resource
    private CenterMapper centerMapper;

    @Autowired
    RoleClient roleClient;

    @Autowired
    private MoudleMapper moudleMapper;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public Organization queryById(Integer id) {
        return this.organizationMapper.selectById(id);
    }

    @Override
    public ResultVO queryByName(String name) {
        QueryWrapper<Organization> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("organization_name", name);
        Organization organization = organizationMapper.selectOne(queryWrapper);
        LinkedHashSet<String> hashSet = new LinkedHashSet<>();
        List<Center> centers = centerMapper.findCenterByOid(organization.getId());
        for (Center center : centers) {
            hashSet.add(center.getCenterName());
        }
        return ResultVO.data(hashSet);
    }

    /**
     * 查询
     *
     * @return 查询结果
     */
    @Override
    public ResultVO queryList() {
        Integer key;
        String websiteId = WebsiteUtil.getWebsiteId();
        if ("4".equals(websiteId)) {
            key = StrategyEnum.Miku.getKey();
        } else {
            key = StrategyEnum.Aqua.getKey();
        }
        return StrategyHandler.getStrategy(key).queryList();
//         List<Organization> organizations;
//         String userId = TokenUserUtil.getCurrentUserId();
//         System.out.println("userId:" + userId);
//         String websiteId = WebsiteUtil.getWebsiteId();
//         System.out.println("websiteId:" + websiteId);
//         String dataRight = roleClient.getDataRight(websiteId, userId);
//         System.out.println("dataRight:" + dataRight);
//         if (StringPool.ONE.equals(dataRight)) userId = null;
//         organizations = organizationMapper.findAllOrganization(userId);
//         organizations.forEach(organization -> {
// /*                if (organization.getPicUrl() != null) {
//                     //String substring = organization.getPicUrl().substring(1, organization.getPicUrl().length() - 1);
//                     //JSONObject jsonObject = JSONObject.parseObject(substring);
//                     JSONArray jsonArray = JSONArray.parseArray(organization.getPicUrl());
//                     organization.setPicUrlJson(jsonArray);
//                 } else {
//                     organization.setPicUrlJson(new JSONArray());
//                 }*/
//             if (organization.getOperateUserId() != null) {
//                 User user = getUser(organization.getOperateUserId());
//                 if (user != null) {
//                     organization.setOperateUserName(user.getUsername());
//                 }
//             }
//             if (StringUtils.isNotBlank(organization.getOrganizationName())) {
//                 organization.setCenterName(organization.getOrganizationName());
//                 organization.setTreeType(NumberConstant.NUMBER_1);
//             }
//             if (organization.getChildren() != null) {
//                 organization.getChildren().forEach(center -> {
//                     if (center.getPi() != null) {
//                         try {
//                             List<Pi> piList = new ArrayList<>();
//                             String[] pis = center.getPi().split(",");
//                             for (String userCode : pis) {
//                                 Pi pi = centerMapper.findCenterByUserCode(userCode);
//                                 if (StringUtils.isNotBlank(pi.getPiInformation())) {
//                                     JSONArray jsonArray = JSONArray.parseArray(pi.getPiInformation());
//                                     pi.setPiInformationJSONArray(jsonArray);
//                                 } else {
//                                     pi.setPiInformationJSONArray(new JSONArray());
//                                 }
//                                 piList.add(pi);
//                                 center.setPiList(piList);
//                             }
//                         } catch (Exception e) {
//                             center.setPiList(null);
//                         }
//                     }
//                     if (center.getAttachementUrl() != null) {
//                         //String s = center.getAttachementUrl().substring(1, center.getAttachementUrl().length() - 1);
//                         //JSONObject jsonObject = JSONObject.parseObject(s);
//                         JSONArray jsonArray = JSONArray.parseArray(center.getAttachementUrl());
//                         center.setAttachementUrlJson(jsonArray);
//                     } else {
//                         center.setAttachementUrlJson(new JSONArray());
//                     }
//                     if (StringUtils.isNotBlank(center.getOperateUserId())) {
//                         User user = getUser(center.getOperateUserId());
//                         center.setOperateUserName(user.getUsername());
//                     }
//                     if (center.getPi() != null) {
//                         String[] split = center.getPi().split(",");
//                         ArrayList<String> pis = new ArrayList<>(Arrays.asList(split));
//                         center.setPis(pis);
//                     }
//                     center.setTreeType(NumberConstant.NUMBER_2);
//                 });
//             }
//         });
//
//         return ResultVO.data(organizations);
    }

    private User getUser(String userId) {
        ResultVO<?> userById = userClient.getUserById(userId);
        JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(userById));
        return JSONObject.parseObject(jsonObject.getString("data"), User.class);
    }


    /**
     * 新增数据
     *
     * @param organization 实例对象
     * @return 实例对象
     */
    @Override
    public ResultVO insert(Organization organization) {
        if (organization == null || organization.getOrganizationName() == null) {
            return ResultVO.fail(ResultCode.PARAM_INVALID);
        }
        if (checkDuplicate(organization)) {
            return ResultVO.fail(ResultCode.ORGANIZATION_DUPLICATION);
        }
        String userId = TokenUserUtil.getCurrentUserId();
        organization.setOperateUserId(userId);
        organization.setIsDeleted(NumberConstant.NUMBER_0);
        organizationMapper.insert(organization);
        return ResultVO.success(ResultCode.SUCCESS);
    }

    /**
     * 修改数据
     *
     * @param organization 实例对象
     * @return 实例对象
     */
    @Override
    public ResultVO update(Organization organization) {
        if (organization == null) {
            return ResultVO.fail(ResultCode.PARAM_INVALID);
        }
        if (queryById(organization.getId()) == null) {
            return ResultVO.fail(ResultCode.SERVE_ERROR);
        }
        if (checkDuplicate(organization)) {
            return ResultVO.fail(ResultCode.ORGANIZATION_DUPLICATION);
        }
        String userId = TokenUserUtil.getCurrentUserId();
        organization.setOperateUserId(userId);
        organizationMapper.updateById(organization);
        return ResultVO.success(ResultCode.SUCCESS);
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public ResultVO deleteById(Integer id) {
        if (id == null) {
            return ResultVO.fail(ResultCode.PARAM_INVALID);
        }
        Organization organization = queryById(id);
        if (organization == null) {
            return ResultVO.fail(ResultCode.SERVE_ERROR);
        }
        organizationMapper.deleteById(id);
        return ResultVO.data(organization.getOrganizationName());
    }

    private boolean checkDuplicate(Organization organization) {
        if (organization.getOrganizationName() != null) {
            QueryWrapper<Organization> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("organization_name", organization.getOrganizationName());
            if (organization.getId() != null) {
                queryWrapper.ne("id", organization.getId());
            }
            List<Organization> organizations = organizationMapper.selectList(queryWrapper);
            return organizations.size() > 0;
        }
        return false;
    }

    @Override
    public ResultVO list() {
        return ResultVO.data(organizationMapper.selectList(null));
    }

    @Override
    public ResultVO queryByOrganizationId(Integer organizationId) {
        if (organizationId == null) {
            return ResultVO.fail(ResultCode.PARAM_INVALID);
        }
        List<Center> centerList = centerMapper.selectList(new LambdaQueryWrapper<Center>().eq(Center::getOrganizationId, organizationId));
        return ResultVO.data(centerList);
    }

    @Override
    public ResultVO queryCenterByModuleId(Integer moduleId) {
        if (moduleId == null) {
            return ResultVO.fail(ResultCode.PARAM_INVALID);
        }
        Moudle moudle = moudleMapper.selectById(moduleId);
        if (moudle == null) {
            return ResultVO.fail(ResultCode.SERVE_ERROR);
        }
        Organization organization = organizationMapper.selectOne(new LambdaQueryWrapper<Organization>().eq(Organization::getId, moudle.getRelevanceId()));
        if (organization == null) {
            return ResultVO.fail(ResultCode.SERVE_ERROR);
        }
        String websiteId = WebsiteUtil.getWebsiteId();
        List<Center> centerByOid = centerMapper.findCenterByOid(organization.getId());
        organization.setChildren(centerByOid);
        if (organization.getOperateUserId() != null) {
            User user = getUser(organization.getOperateUserId());
            if (user != null) {
                organization.setOperateUserName(user.getUsername());
            }
        }
        if (StringUtils.isNotBlank(organization.getOrganizationName())) {
            organization.setCenterName(organization.getOrganizationName());
            organization.setTreeType(NumberConstant.NUMBER_1);
        }
        if (organization.getChildren() != null) {
            organization.getChildren().forEach(center -> {
                if ((center.getPi() != null && WebsiteUtil.hasAccessToken()) || StringPool.ONE.equals(websiteId)) {
                    try {
                        List<Pi> piList = new ArrayList<>();
                        String[] pis = center.getPi().split(",");
                        for (String userCode : pis) {
                            Pi pi = centerMapper.findCenterByUserCode(userCode, websiteId);
                            if (pi.getIsVerified() == 0) continue;
                            if (StringUtils.isNotBlank(pi.getPiInformation())) {
                                JSONArray jsonArray = JSONArray.parseArray(pi.getPiInformation());
                                pi.setPiInformationJSONArray(jsonArray);
                            } else {
                                pi.setPiInformationJSONArray(new JSONArray());
                            }
                            piList.add(pi);
                            center.setPiList(piList);
                        }
                    } catch (Exception e) {
                        center.setPiList(null);
                    }
                }
                if (center.getAttachementUrl() != null) {
                    JSONArray jsonArray = JSONArray.parseArray(center.getAttachementUrl());
                    center.setAttachementUrlJson(jsonArray);
                } else {
                    center.setAttachementUrlJson(new JSONArray());
                }
                if (StringUtils.isNotBlank(center.getOperateUserId())) {
                    User user = getUser(center.getOperateUserId());
                    center.setOperateUserName(user.getUsername());
                }
                if (center.getPi() != null && WebsiteUtil.hasAccessToken() || StringPool.ONE.equals(websiteId)) {
                    String[] split = center.getPi().split(",");
                    ArrayList<String> pis = new ArrayList<>(Arrays.asList(split));
                    center.setPis(pis);
                } else {
                    center.setPi(null);
                }
                center.setTreeType(NumberConstant.NUMBER_2);
            });
        }
        return ResultVO.data(organization);
    }
}
